var current;

window.onload = function() {

	getManagers();

	$('#myModal').on('shown.bs.modal', function () {
		$('#myInput').focus()
	});

	setInterval(function() {
		getSpiders();
	}, 5*1000);
}

function getSpiders() {
	$body = $("#spiders");
	$.get("/running", function(data) {
		$body.empty();
		$.each(data, function(i, elt) {
			$body.append("<tr>"
					+"<td><input type=\"checkbox\" item=\"manager\" value=\"+(i+1)+\"/></td>"
					+"<td>"+(i+1)+"</td>"
					+"<td>"+elt.name+"</td>"
					+"<td>"+elt.topic+"</td>"
					+"<td>"+elt.regx+"</td>"
					+"<td>"+(elt.status?"运行中":"等待启动")+"</td>"
					+"<td>"+elt.priority+"</td>"
					+"<td><a href=\"#\">添加目标网站</a></td>"
					+"<td>"+elt.count+"</td>"
					+"<td><a href=\"javascript:run('"+elt.name+"',true)\">启动</a>&nbsp;<a href=\"javascript:run('"+elt.name+"',false)\">停用</a></td>"
			);

		})
		getThemes();
	});
}

function addUrl() {
	$url = $("#recipient-name").val();
	$topic = $("select[name=topic]").val();
	$.get("start_url", {topic:$topic,url:$url}, function(data) {
		if(data) {
			alert("添加成功")
		}
	})
}

function getThemes() {
	$body = $("#urls");
	$item = $("select[name=topic]");
	$item.empty();
	$.get("themes",function(data){
		$body.empty();
		$.each(data, function(i, elt) {
			if(data) {
				if(elt.start_Url) {
					$urls = elt.start_Url;
					$list = "";
					for(var j in $urls) {
						$list += $urls[j]+"<br/>";
					}
				} else
					$list = "..."
						$body.append("<tr>"
								+"<td><input type=\"checkbox\" item=\"manager\" value=\"+(i+1)+\"/></td>"
								+"<td>"+(i+1)+"</td>"
								+"<td>"+elt.topic+"</td>"
								+"<td>"+elt.spiderNum+"</td>"
								+"<td>"+$list+"</td>"
								+"<td>无</td>"
								+"<td>2周</td>"
								+"<td>数据库</td>"
								+"<td>已关闭</td>"
								+"<td><a href=\"#\">调用</a>&nbsp;<a href=\"javascript:run('"+elt.name+"',false)\">停用</a></td>"
						);
				$item.append("<option value=\""+elt.topic+"\">"+elt.topic+"</option>")
			}
		})
	})
}

function getManagers() {
	$body = $("#managers");
	$.get("/managers", function(data) {
		$body.empty();
		$.each(data, function(i, elt) {
			var index = elt.driver.lastIndexOf('.'); 
			$body.append("<tr>"
					+"<td><input type=\"checkbox\" item=\"manager\" value=\"+(i+1)+\"/></td>"
					+"<td>"+(i+1)+"</td>"
					+"<td>127.0.0.1</td>"
					+"<td>"+elt.topic+"</td>"
					+"<td>"+elt.regx+"</td>"
					+"<td>"+elt.count+"</td>"
					+"<td><a href=\"javascript:start_spider('"+elt.topic+"')\"><span class=\"glyphicon glyphicon-play\"></span>启动</a>&nbsp;&nbsp;<a href=\"\"><span class=\"glyphicon glyphicon-wrench\" aria-hidden=\"true\"></span>修改</a></td>"

			);
		})
		getSpiders();
	});
}

function run(name,flag) {
	$.post("start", {name:name,flag:flag}, function(data) {
		getSpiders();
	})
}

function start_spider(topic) {
	$.get("registery",
			{
		theme:topic
			},
			function(data){
				if(data) {
					getManagers();
				}
			}
	);
}